package controllers

import (
	"beego/service"
	"context"
	"fmt"
	"github.com/astaxie/beego"
	"github.com/olivere/elastic/v7"
	"log"
	"os"
)

type EsearchController struct {
	beego.Controller
}

var client *elastic.Client
var host = beego.AppConfig.String("esHost")

func init() {
	errorlog := log.New(os.Stdout, "APP", log.LstdFlags)
	var err error
	client, err = elastic.NewClient(elastic.SetErrorLog(errorlog), elastic.SetURL(host))
	if err != nil {
		panic(err)
	}
	info, code, err := client.Ping(host).Do(context.Background())
	if err != nil {
		panic(err)
	}
	fmt.Printf("Elasticsearch returned with code %d and version %s .", code, info.Version.Number)

	esversion, err := client.ElasticsearchVersion(host)
	if err != nil {
		panic(err)
	}
	fmt.Printf("Elasticsearch version %s .", esversion)
}

type Employee struct {
	FirstName string   `json:"first_name"`
	LastName  string   `json:"last_name"`
	Age       int      `json:"age"`
	About     string   `json:"about"`
	Interests []string `json:"interests"`
}

/**
 * 根据id直查es数据(单条)
 */

func (c *EsearchController) Get() {
	Id := c.GetString("id", "8798853f1bc8eef5cf3dcd83faccc3d1")
	// 查询ES数据
	esGet, err := client.Get().Index("xgwx_literature_subscribe").Type("_doc").
		Id(Id).Do(context.Background())
	if err != nil {
		panic(err)
	}

	if esGet.Found {
		_ = fmt.Sprintf("Got document %s in version %d from index %s, type %s", esGet.Id, esGet.Version, esGet.Index, esGet.Type)
	}

	//es(_source为json数据)数据转map
	var r service.Request
	r.Req = string(esGet.Source)
	req2map, err := r.Json2map()
	if err == nil {
		fmt.Println(req2map)
	} else {
		fmt.Println(err)
	}
	DataMap := make(map[string]interface{})
	DataMap["esData"] = req2map

	DataMap["doc"] = esGet
	// JSON数据处理
	ret := service.ReturnMsg{Code: 200, Msg: "Success", Data: DataMap}
	c.Data["json"] = ret
	c.ServeJSON() // 对json进行序列化输出
	c.StopRun()
}

/**
 * 根据关键词之查es数据
 */

func (c *EsearchController) Search() {
	client.Ping(host).Do(context.Background())

	var res *elastic.SearchResult
	//条件查询(boolQ 无效)
	q := elastic.NewQueryStringQuery("title:Effects of")
	/*boolQ := elastic.NewBoolQuery()
	boolQ.Must(elastic.NewMatchQuery("title", "Effects of"))
	boolQ.Must(elastic.NewMatchQuery("doi", "10.1016/"))
	boolQ.Filter(elastic.NewRangeQuery("pmid").Gt(10))*/
	res, _ = client.Search("xgwx_literature_subscribe").Type("_doc").Query(q).Do(context.Background())
	DataMap := make(map[string]interface{})
	DataMap["List"] = res
	// JSON数据处理
	ret := service.ReturnMsg{Code: 200, Msg: "Success", Data: DataMap}
	c.Data["json"] = ret
	c.ServeJSON() // 对json进行序列化输出
	c.StopRun()
}
